from django.http import HttpResponse
from django.shortcuts import render, redirect
from app01 import models
import json
from urllib import parse
from django.views.decorators.csrf import csrf_exempt
import difflib
import hashlib
import os
from queue import Queue

def mayinterest(request):
    workLst = calculate()
    lst = []
    for ob in workLst:
        name = ob.workname
        time = ob.time
        description = ob.description
        id = ob.md5
        contentCode = ob.contentCode
        contentPaper = ob.contentPaper
        contributor = ob.contribute
        field = ob.chosens
        now = {
            "name": name,
            "id": id,
            "time": time,
            "description": description,
            "content": contentCode,
            "num": contributor,
            "field": field
        }
        lst.append(now)
    jon = {
        'recommand':lst
    }
    return HttpResponse(json.dumps(jon))
    return HttpResponse('success')

# Create your views here.
@csrf_exempt
def startwork(request):
    if request.method == 'GET':
        return render(request,'startwork.htm',{})
    else:
        user = request.COOKIES['username']
        workname = request.POST.get('workname')
        description = request.POST.get('description')
        chosens = request.POST.get('chosens')
        md5 = hashlib.md5(user.encode()).hexdigest()
        work = {
            'md5':md5,
            'username':user,
            'workname':workname,
            'description':description,
            'chosens':chosens,
        }
        if(len(models.Work.objects.filter(username=user, workname=workname)) == 0):
            models.Work.objects.create(**work)
        else:
            return HttpResponse("unsuccess!")
        return render(request,'startwork.htm',{})
@csrf_exempt
def star(request):


    return HttpResponse('success')

@csrf_exempt
def create(request):
    user = request.COOKIES['username']
    workname = request.POST.get('workname')
    description = request.POST.get('description')
    chosens = request.POST.get('chosens')
    md5 = hashlib.md5(user.encode()).hexdigest()
    work = {
            'md5':md5,
            'username':user,
            'workname':workname,
            'description':description,
            'chosens':chosens,
    }
    if(len(models.Work.objects.filter(username=user, workname=workname)) == 0):
        models.Work.objects.create(**work)
    return HttpResponse(md5)

@csrf_exempt
def remove(request):
    extract = request.body.decode('utf8')
    m = models.Work.objects.all()
    for ob in m:
        if(ob.username == request.COOKIES['username'] and extract == ob.workname):
            ob.delete()
            return HttpResponse('success')
    return HttpResponse('success')

def myworkjson(request):
    m = models.Work.objects.all()
    user = request.COOKIES['username']
    us = models.User.objects.get(username=user)
    profile = us.profile
    lst = []
    for ob in m:
        if(ob.username == user):
            name = ob.workname
            time = ob.time
            description = ob.description
            id = ob.md5
            contentCode = ob.contentCode
            contentPaper = ob.contentPaper
            contributor = ob.contribute
         #   contentCode = contentCode, 'code', contentPaper, 'paper'
            field = ob.chosens
            now = {
                "name": name,
                "id": id,
                "time": time,
                "description": description,
                "content": contentCode,
                "num": contributor,
                "field": field
            }
            lst.append(now)
    jon = {
        'username':user,
        'profile':profile,
        'recommand':lst
    }
    return HttpResponse(json.dumps(jon))

def workjs(request):
    return render(request,'mayinterest.json',{})
    if request.method == 'GET':
        m = models.Work.objects.all()
        user = request.COOKIES['username']
        us = models.User.objects.get(username=user)
        profile = us.profile
        lst = []
        for ob in m:
            if(ob.username == user):
                name = ob.workname
                time = ob.time
                description = ob.description
                id = ob.md5
                contentCode = ob.contentCode
                contentPaper = ob.contentPaper
                contributor = ob.contribute
                field = ob.chosens
                now = {
                    "name": name,
                    "id": id,
                    "time": time,
                    "description": description,
                    "content": contentCode,
                    #"content": contentCode + ' code'+contentPaper+' paper',
                    "num": contributor,
                    "field": field
                }
                lst.append(now)
        jon = {
            'username':user,
            'profile':profile,
            'recommand':now
        }
    return HttpResponse(json.dumps(jon))

def mywork(request):
    
    return render(request,'mywork.htm',{})

def detail(request):
    return render(request,'detail.htm',{})

def calculate():
    m = models.Work.objects.all()
    n = models.User.objects.get(username='111111')
    lst = []
 #   print(n.interested)
    ans = []
    for ob in m:
       if(ob.username != '123'):
           similarity = difflib.SequenceMatcher(None, ob.chosens, n.interested).quick_ratio()

           lst.append((ob,similarity))
    print(ans)
    i = 0
    while i < 1:
       ans.append(lst[i][0])
       i += 1
    print(ans)
    return ans
       #print( difflib.SequenceMatcher(None, ob.interested, n.interested).quick_ratio())
#    print(m)

def cover(request):
    return render(request,'cover.htm',{})

def explore(request):
    return render(request,'explore.htm',{})

# 登录
@csrf_exempt
def login(request):
    if request.method == 'GET':
        calcu()
        return render(request, 'signin.htm')
    elif request.method == 'POST':
        # 验证用户名密码是否正确，然后登陆存入session
        type = request.POST.get('type')
       # response = {'msg': '', 'status': False}
        username = request.POST.get('username')
        password = request.POST.get('password')
        if(len(username) == 0):
            return HttpResponse('请输入账号')
        if(len(password) == 0):
            return HttpResponse('请输入密码')
        print(username)
        print(password)
    #    return HttpResponse('success')
        if type == 'login':
            if len(models.User.objects.filter(username=username, password=password)) != 0:
                return HttpResponse('success')
                # 登录成功

            else:
                # 登录失败
            #    response['msg'] = '用户名或者密码错误'
                return HttpResponse('用户名或者密码错误')

# 注册
def register(request):
    if request.method == 'GET':
        return render(request,'register1.htm',{})
    if request.method == 'POST':
        
        # 判断是否已有
        uid = request.POST.get('uid')
        pwd = request.POST.get('pwd')
        if len(models.User.objects.filter(uid=uid)) != 0:
            return render(request, 'login.html', {'message': '用户名已被创建'})
        else:
            # 插入数据
            user = {
                'uid': uid,
                'password': pwd,
            }
            models.User.objects.create(**user)
            return redirect('/home')
def register1(request):
    return render(request,'register1.htm',{})
@csrf_exempt
def register2(request):
    if request.method == 'GET':
        return render(request,'register2.htm',{})
    elif request.method == 'POST':
        username = request.POST.get('username')
        password =  request.POST.get('password')
        email = request.POST.get('email')
        organization = request.POST.get('organization')
        education = request.POST.get('education')
        working = request.POST.get('working')
        interested = request.POST.get('interested')
        profile = request.POST.get('profile')
        print(len(profile) )
        if(  len(profile) == 1527 ):
            return HttpResponse('请上传头像')
        print(username)
        
        
        if len(models.User.objects.filter(username=username)) != 0:
            return HttpResponse('用户名已被创建!')
        
        else:
            user = {
                'username':username,
                'password':password,
                'email':email,
                'organization':organization,
                'education':education,
                'working':working,
                'interested':interested,
                'profile':profile,
            }
            models.User.objects.create(**user)
            print('注册成功')
        
        return HttpResponse('success')

def register3(request):
        return render(request,'register3.htm',{})




# 管理员登录
def admin(request):
    if request.method == 'GET':
        return render(request, 'admin.html')
    elif request.method == 'POST':
        admin_uid = request.POST.get('admin_id')
        admin_pwd = request.POST.get('admin_pwd')

        response = {'msg': '', 'status': False}

        if admin_uid == 'guanliyuan' and admin_pwd == '123456':
            # 管理员登录成功
            response['status'] = True
            request.session['admin_uid'] = 'guanliyuan'
            return HttpResponse(json.dumps(response))
        else:
            response['msg'] = '用户名或者密码错误'
            return HttpResponse(json.dumps(response))



